var util = require('../../utils/util.js');
var ajax = require('../../utils/ajax.js');
var common = require('../../utils/common.js');
var PageBase = require('../../common/PageBase.js');
var app = getApp();

Page(common.extendPage(PageBase, {
  data: {
    allLoaded: false,
    isLoadMore: false,
    noMore: false,
    allSelected: false,
    page: 1,
    shopIndex: 0,
    cartList: [],
    loading: true,
    mustLogin: false
  },
  /**
   * 页面初始化
   */
  onLoad(options) {},
  /**
   * 页面重载
   */
  onShow() {
    console.log(new Date());
    if (!!wx.getStorageSync('uid')) {
      this.flush(true);
    } else {
      this.setData({
        mustLogin: true
      })
    }
  },
  /**
   * 下拉加载更多
   */
  onReachBottom() {
    this.loadMore()
  },
  _minus(evt) {
    this.count(evt, false);
  },
  _plus(evt) {
    this.count(evt, true);
  },
  count(evt, flag) {
    let {
      currentNum,
      parentIndex,
      index
    } = evt.currentTarget.dataset;

    let list = this.data.list;
    let goodsNum = list[parentIndex].items[index].num;
    let goodsAmount = list[parentIndex].items[index].amount;
    flag ? currentNum++ : currentNum--;
    goodsNum = currentNum;
    list[parentIndex].items[index].num = goodsNum;
    if (currentNum < 1) {
      goodsNum = 1;
      util.tips('商品最小购买数量不得小于1');
      return false;
    }
    if (currentNum > goodsAmount) {
      goodsNum = goodsAmount;
      util.tips('商品最大购买数量不得大于商品库存');
      return false;
    }
    this.setData({
      list
    })
  },
  /**
   * 商品选择切换
   */
  _switchTabs(evt) {
    let {
      parentIndex,
      index
    } = evt.currentTarget.dataset;
    let list = this.data.cartList;
    let shopIndex = this.data.shopIndex;

    let listSub = list[parentIndex].services.item;
    let listItem = list[parentIndex];
    let listSubItem = listSub[index];
    if (index === undefined) {
      /**支持单选的情况 */
      list.forEach((item, index) => {
        item.isSelected = false;
        item.services.item.forEach((val, idx) => {
          val.isSelected = false;
        })
      })

      listItem.isSelected = true;
      listSub.forEach((item, index) => {
        item.isSelected = listItem.isSelected;
      })
      /**支持多选的情况 */
      // listItem.selected = !listItem.selected;
      // listSub.forEach((item, index) => {
      //   item.selected = listItem.selected;
      // })
    } else {
      if (shopIndex != parentIndex) {
        list[shopIndex].isSelected = false;
        list[shopIndex].services.item.forEach((val, idx) => {
          val.isSelected = false;
        })
      }
      if (list[parentIndex].services.item.filter((val, idx) => {
          return val.isSelected == true;
        }).length == 1) {
        list[parentIndex].services.item[index].isSelected = true;
      } else {
        list[parentIndex].services.item[index].isSelected = !list[parentIndex].services.item[index].isSelected;
      }

      if (list[parentIndex].services.item.findIndex((val, idx) => {
          return val.isSelected === false;
        }) == -1) {
        list[parentIndex].isSelected = true;
      } else {
        list[parentIndex].isSelected = false;
      }

      list[parentIndex].services.item.filter((val, idx) => {
        return val.isSelected == true;
      });
    }

    // this.checkAllSelected();
    this.setData({
      cartList: list,
      shopIndex: parentIndex
    })
  },
  /**
   * 全选
   */
  _selectedAll() {
    let allSelected = this.data.allSelected;
    let list = this.data.list;
    list.forEach((item, index) => {
      item.selected = !allSelected;
      item.items.forEach((val, idx) => {
        val.selected = !allSelected;
      })
    })
    this.setData({
      allSelected: !allSelected,
      list
    })
  },
  /**
   * 删除
   */
  _del() {
    var list = this.data.cartList;
    var paramsUrl = '/public/api/orders/delcarts';
    var paramsData = {
      uid: wx.getStorageSync('uid'),
      offset: ''
    }
    var offsetArr = [];
    list.some((item, index) => {
      item.services.item.forEach((val, idx) => {
        if (val.isSelected) {
          paramsData.mid = item.mid;
          offsetArr.push(idx);
        }
      })
      paramsData.offset = offsetArr.join(',');
    })
    ajax.P({
      url: paramsUrl,
      data: paramsData,
      success: (res) => {
        util.tips('删除成功', () => {
          this.flush();
        });
      }
    })
  },
  checkAllSelected: function() {
    var list = this.data.list;
    var isAllSelected = false;
    var hasNoSelected = list.some(function(item) {
      if (!item.selected) {
        return true;
      }
    });

    if (!hasNoSelected) {
      isAllSelected = true;
    }
    this.setData({
      allSelected: isAllSelected
    });
  },
  /**
   * 刷新
   */
  flush(isInit) {
    this.setData({
      page: 1,
      allLoaded: false,
      noMore: false
    });

    this.getCartList(true, false, () => {
      wx.stopPullDownRefresh();
      if (isInit) {
        this.setData({
          loading: false,
          mustLogin: false
        })
      }
    });
  },
  /**
   * 加载更多
   */
  loadMore() {
    var {
      allLoaded,
      currentTab
    } = this.data;

    if (allLoaded) {
      return;
    } else {
      this.setData({
        isLoadMore: true
      })

      this.getCartList(false, true, () => {
        this.setData({
          dataLoaded: true,
          isLoadMore: false
        })
      });
    }
  },
  /**
   * 获取购物车列表
   */
  getCartList(isFlush, unneedLoad, cb) {
    var cartList = this.data.cartList;
    var page = this.data.page;
    var shopIndex = this.data.shopIndex;
    var paramsUrl = '/public/api/orders/cartlist';
    var paramsData = {
      uid: wx.getStorageSync('uid'),
      page: page || 1,
      num: 10
    };
    ajax.P({
      url: paramsUrl,
      data: paramsData,
      success: (res, isLoadcb) => {
        var listData = res.list || [];
        var allLoaded = false;
        var noMore = false;

        if (listData) {
          if (listData.length == 0) {
            allLoaded = true;
            noMore = true;
          } else {
            listData.forEach((item, index) => {
              item.isSelected = false;
              item.services.item.forEach((val, idx) => {
                val.isSelected = false;
                var servicesDes = [];
                val.amount = parseFloat(val.amount).toFixed(2);
                if (val.services && val.services.length > 0) {
                  val.services.forEach((o, i) => {
                    servicesDes.push(o.split(',')[0]);
                  })
                  if (item.storetype == 1 || item.storetype == 8) {
                    val.des = val.species + '+' + val.ways + '+' + val.specifications + '+' + servicesDes.join('/');
                  } else if (item.storetype == 2 || item.storetype == 9) {
                    val.des = val.specifications + '+' + servicesDes.join('/');
                  } else {
                    val.des = servicesDes.join('/');
                  }
                }
              })
            })
          }
        }

        if (isFlush) {
          cartList = listData;
          if(cartList.length > 0){
            shopIndex = 0;
            cartList[0].isSelected = true;
            cartList[0].services.item.forEach((item, index) => {
              item.isSelected = true;
            })
          }
        } else {
          cartList = cartList.concat(listData);
          shopIndex = this.data.shopIndex;
        }
        this.setData({
          cartList,
          page: ++page,
          allLoaded,
          noMore,
          shopIndex
        })
        console.log(this.data.cartList);
        isLoadcb && isLoadcb();
        cb && cb();
      },
      fail: (res) => {
        console.log(res);
      },
      unneedLoad
    })
  },
  /**
   * 跳转到下单页面
   */
  _jumpM() {
    var url = "/pages/confirm/index";
    var {
      cartList,
      shopIndex
    } = this.data;
    var curCartItem = {};
    var curCartSericeItem = [];
    var way = [{
      name: '干洗',
      isSelected: false
    }, {
      name: '水洗',
      isSelected: false
    }]

    var clothesSku = [{
      name: '普通洗衣',
      isSelected: false
    }, {
      name: '精品洗衣',
      isSelected: false
    }, {
      name: '高档洗衣',
      isSelected: false
    }];

    var shoesSku = [{
        name: '普通洗鞋',
        isSelected: false
      },
      {
        name: '精品洗鞋',
        isSelected: false
      },
      {
        name: '高档洗鞋',
        isSelected: false
      }
    ];
    cartList.some((item, index) => {
      if (item.isSelected) {
        curCartItem = item;
        console.log(curCartItem);
      }
    })
    curCartItem.services.item.forEach((item, index) => {
      item.way = item.ways;
      if (item.isSelected) {
        curCartSericeItem.push(item);
      }
    })
    curCartSericeItem.forEach((item, index) => {
      this._subtotalPrice = 0;
      var servicesArr = [];
      var services = [];
      if (cartList[shopIndex].storetype == 1 || cartList[shopIndex].storetype == 8) {
        way[0].skuItem = item.infos.specifications.dry;
        way[1].skuItem = item.infos.specifications.water;
        way.some((val, idx) => {
          if (val.name == item.ways) {
            item.wayPrice = val.price;
            val.isSelected = true;
            /*this._subtotalPrice += parseFloat(val.price)*//*****/;
          }
        })
        way.forEach((item, index) => {
          if (item.isSelected) {
            console.log(Object.values(item.skuItem));
            Object.values(item.skuItem).forEach((val, idx) => {
              if (!val) {
                clothesSku.splice(index, 1);
              } else {
                clothesSku[idx].price = val;
              }
            })
          }
        })
  
        clothesSku.some((val, idx) => {
          if (val.name == item.specifications) {
            item.specificationsPrice = val.price;
            val.isSelected = true;
            this._subtotalPrice += parseFloat(val.price);
          }
        })

        item.psfee = item.infos.psfee.psfee;
      }
      if (cartList[shopIndex].storetype == 2 || cartList[shopIndex].storetype == 9) {
        way[0].skuItem = item.infos.specifications.dry;
        way[1].skuItem = item.infos.specifications.water;
        way.some((val, idx) => {
          if (val.name == item.ways) {
            item.wayPrice = val.price;
            val.isSelected = true;
          }
        })
        way.forEach((item, index) => {
          if (item.isSelected) {
            console.log(Object.values(item.skuItem));
            Object.values(item.skuItem).forEach((val, idx) => {
              if (!val) {
                shoesSku.splice(index, 1);
              } else {
                shoesSku[idx].price = val;
              }
            })
          }
        })
        shoesSku.some((val, idx) => {
          if (val.name == item.specifications) {
            item.specificationsPrice = val.price;
            val.isSelected = true;
            this._subtotalPrice += parseFloat(val.price);
          }
        })

        item.psfee = item.infos.psfee.psfee;
      }
      if (cartList[shopIndex].storetype == 5 || cartList[shopIndex].storetype == 6) {
        this._subtotalPrice = parseFloat(item.infos.plat_fee).toFixed(2);
      }
      if (cartList[shopIndex].storetype == 3) {
        item.distance = item.infos.distance;
        item.handling = item.infos.handling;
        item.jiashou = item.infos.jiashou;
      }
      if (item.services && item.services.length > 0) {
        item.services.forEach((val, idex) => {
          servicesArr.push(val.split(','));
        })
      }
      servicesArr.forEach((val, idx) => {
        var servicesInfo = {};
        servicesInfo.title = val[0];
        servicesInfo.unit = val[1];
        servicesInfo.price = val[2],
          servicesInfo.num = val[3];
        servicesInfo.subtotalPrice = val[2] * val[3];
        services.push(servicesInfo);
      })
      services.forEach((val, idx) => {
        this._subtotalPrice += parseFloat(val.subtotalPrice);
      })
      item.subtotalPrice = this._subtotalPrice;
      item.services = services;
      console.log(item);
    })
    console.log(cartList,cartList[shopIndex],'*****');
    url += '?mid=' + cartList[shopIndex].mid + '&cid=' + cartList[shopIndex].id + '&shopName=' + cartList[shopIndex].company + '&storetype=' +
      cartList[shopIndex].storetype + '&depot=' + JSON.stringify(curCartSericeItem);
    console.log(url);
    wx.navigateTo({
      url
    })
  }
}));